//
//  ImagePreview.java
//  
//
//  Borrowed from Sun tutorial:
//	http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html

package wosaic.utilities;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;

/**
 * An accessory that can be added to a JFileChooser to display a small preview
 * of the selected image.
 * 
 * Based on ImagePreview.java by FileChooserDemo2.java.
 */
public class ImagePreview extends JComponent implements PropertyChangeListener {
	/**
	 * Generated by Eclipse
	 */
	private static final long serialVersionUID = -1118759912160048880L;
	File file = null;
	ImageIcon thumbnail = null;

	/**
	 * Default constructor
	 * 
	 * @param fc
	 *            the filechooser we will associate with
	 */
	public ImagePreview(final JFileChooser fc) {
		setPreferredSize(new Dimension(100, 50));
		fc.addPropertyChangeListener(this);
	}

	/**
	 * Create an ImageIcon for the currently selected image, if applicable
	 */
	public void loadImage() {
		if (file == null) {
			thumbnail = null;
			return;
		}

		// Don't use createImageIcon (which is a wrapper for getResource)
		// because the image we're trying to load is probably not one
		// of this program's own resources.
		final ImageIcon tmpIcon = new ImageIcon(file.getPath());
		if (tmpIcon.getIconWidth() > 90)
			thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90,
					-1, Image.SCALE_DEFAULT));
		else
			thumbnail = tmpIcon;
	}

	/**
	 * Paint our preview icon to the screen
	 * 
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	protected void paintComponent(final Graphics g) {
		if (thumbnail == null)
			loadImage();
		if (thumbnail != null) {
			int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
			int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;

			if (y < 0)
				y = 0;

			if (x < 5)
				x = 5;
			thumbnail.paintIcon(this, g, x, y);
		}
	}

	public void propertyChange(final PropertyChangeEvent e) {
		boolean update = false;
		final String prop = e.getPropertyName();

		// If the directory changed, don't show an image.
		if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
			file = null;
			update = true;

			// If a file became selected, find out which one.
		} else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
			file = (File) e.getNewValue();
			update = true;
		}

		// Update the preview accordingly.
		if (update) {
			thumbnail = null;
			if (isShowing()) {
				loadImage();
				repaint();
			}
		}
	}
}
